package com.ingenico.insider.services.impl;

import java.awt.Color;
import java.util.MissingResourceException;
import java.util.logging.Logger;

import com.ingenico.insider.util.Constants;

public final class CyclicColorsSupplier {
	private static final Logger _logger = Logger.getLogger(CyclicColorsSupplier.class.getCanonicalName());

	public static final String NB_CUSTOM_COLORS = Constants.INSIDER_BASE + Constants.SEPARATOR + "nb_custom_colors";
	public static final String COLOR_PATH    = Constants.INSIDER_BASE + Constants.SEPARATOR + "color_";

	private static int colorIndex = 0;
	private static Color[] availableColors;

	/**
	 * singleton instance
	 */
	private static CyclicColorsSupplier instance;
	
	/**
	 * private constructor of final class to prevent external instantiation
	 */
	private CyclicColorsSupplier() {
		initColors();
	}

	private void initColors() {
		final UserPreferencesSupplier userPreferencesSupplier = UserPreferencesSupplier.getInstance();
		int nbUserColors = 0;
		try {
			nbUserColors = userPreferencesSupplier.getInstance().getDecimal(NB_CUSTOM_COLORS).intValue();
	
			if (nbUserColors <= 0) {
				throw new IllegalArgumentException("User Preference Key Invalid (" + NB_CUSTOM_COLORS + "). There must be at least one custom color");
			}
		} catch (MissingResourceException mre) {
			availableColors = new Color[] {
				Color.RED
			};
		}

		// If the user has defined colors then we must initialize the array
		if (nbUserColors > 0) {
			availableColors = new Color[nbUserColors];
			for(int i=0; i< nbUserColors; i++) {
				availableColors[i] = userPreferencesSupplier.getColor(COLOR_PATH + i);
			}
		}
	}

	/**
	 * retrieve the singleton instance
	 *
	 * @return the CyclicColorsSupplier singleton
	 */
	public static CyclicColorsSupplier getInstance() {
		if (instance == null) {
			_logger.info(CyclicColorsSupplier.class.getName() + " instance does not exist... Creating instance.");
			instance = new CyclicColorsSupplier();
		}
		return instance;
	}
	
	public static Color getNext() {
		return availableColors[colorIndex++%(availableColors.length)];
	}
}
